package com.hc.android.research.views;

import java.io.InputStream;
import java.net.URL;

import com.hc.android.research.R;
import com.hc.android.research.persistence.ResearchDAO;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AddData extends Activity implements OnClickListener
{

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adddata);
        
        Button addBtn = (Button)findViewById(R.id.addBtn);
        addBtn.setOnClickListener(this);
    }
    
    @Override
    protected void onPause() 
    {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }

	public void onClick(View v) 
	{
		try
		{
			((TextView)findViewById(R.id.errorTxt)).setText("");
			
			String url = ((TextView)findViewById(R.id.urlTxt)).getText().toString();
			String name = ((TextView)findViewById(R.id.nameTxt)).getText().toString();
			if(isValidURL(url))
			{
				ResearchDAO researchDAO = new ResearchDAO();
				researchDAO.addItem(this, name, url);
				
				((TextView)findViewById(R.id.urlTxt)).setText("");
				((TextView)findViewById(R.id.nameTxt)).setText("");
				((TextView)findViewById(R.id.errorTxt)).setText(R.string.urlAdded);
			}
			else
			{
				((TextView)findViewById(R.id.errorTxt)).setText(R.string.urlOrNameError);
			}
		}
		catch(Exception e)
		{
			((TextView)findViewById(R.id.errorTxt)).setText(R.string.urlOrNameError);			
		}	
		
	}

	private boolean isValidURL(String url)
	{
		boolean result = false;
		
		try
		{
			if(!url.startsWith("www."))
			{
				url = "www." + url;
			}
						
			if(!url.startsWith("http://") || !url.startsWith("https://"))
			{
				url = "http://" + url;
			}
			
			URL urlObj = new URL(url);
			InputStream stream = urlObj.openStream();
			stream.close();
			
			result = true;
		}
		catch(Exception e)
		{
			result = false;
		}
		
		return result;
	}
}
